<script>
import Form from '../rewardPunishmentForm/RewardPunishment'
import { getAllUser } from '@/api/personnel'
import { editRecord,getPunishment } from '@/api/punishment'
export default {
    components: {
        Form
    },
    props:{
        id:{
            required:true,
            default(){
                return null;
            }
        },
        value:{
            type:Boolean,
            required:true,
            default(){
                return false
            }
        }
    },
    emits:['success','failed'],
    data() {
        return {
            form:{
                employeeID:null,
                reason:'',
                amount:null,
                type:null,
                publishing_mode:null,
                public_type:null,
                isMonth:null
            },
            employeeOptions:[],
            isSubmitting:false,
            isLoading:false
        }
    },
    computed:{
        visible:{
            get(){
                return this.value   
            },
            set(visible){
                this.$emit('input',visible)
            }
        },
        isShow(){
            return this.visible && typeof this.id === 'number'
        },
        isActionDisabled(){
            return this.isSubmitting || this.isLoading
        }
    },
    watch:{
        isShow(v){
            if(!v)return
            this.initData()
        }
    },
    methods:{
        deserialize(data){
            const { amount,content,type,user,is_month,publishing_mode,public_type } = data
            console.log(data,'data');
            this.form = {
                amount:parseFloat(amount)||0,
                reason:content,
                type,
                employeeID:user.id,
                isMonth:is_month,
                publishing_mode:publishing_mode,
                public_type:public_type
            }
        },
        handleClose(callback){
            callback(!this.isSubmitting)
        },
        closeDialog(){
            if(this.isSubmitting)return
            this.visible = false
        },
        sleep(t){
            return new Promise(r => setTimeout(r,t))
        },
        buildParams(){
            const { employeeID,reason,amount,isMonth,type,publishing_mode,public_type } = this.form
            return {
                id:this.id,
                user_id:employeeID,
                content:reason,
                amount,
                type,
                is_month:isMonth,
                publishing_mode:publishing_mode,
                public_type:public_type
            }
        },
        handleConfirm(){
            this.$refs.form.validate(async flag => {
                if(!flag)return

                try {
                    this.isSubmitting = true
                
                    const params = this.buildParams()
                    let result = await editRecord(params)

                    this.isSubmitting = false

                    if(result.code !== 200)
                        throw new Error(result.message ?? '创建失败')

                    this.visible = false
                    this.$refs.form?.resetFields()
                    this.$emit('success')
                }catch(e){
                    this.isSubmitting = false
                    this.$emit('false')
                }

            })
        },
        async initData(){
            try {
                this.isLoading = true
                await this.sleep(200)
                await this.loadData()
                this.isLoading = false
            }catch(e){
                this.isLoading = false
            }
        },
        async loadData(){
            let result = await Promise.allSettled([
                this.getPunishment(),
                this.fetchEmployees()
            ])
            let failTasks = result.filter(task => task.status === 'rejected')
            if(failTasks.length > 0)
                throw failTasks[0].reason
        },
        async getPunishment(){
            let result = await getPunishment(this.id)

            if(result.code !== 200)
                throw new Error(result.message ?? '获取奖惩详情失败')

            this.deserialize(result.data)
            console.log(result)
        },
        async fetchEmployees(kw){
            let result = await getAllUser({
                username: kw,
                type:2
            })

            if(result.code !== 200)
                throw new Error(result.message ?? '获取失败')

            this.employeeOptions = result.data.map(item => {
                const { id,username } = item
                return {
                    label:username,
                    value:id
                }
            })
        }
    }
}
</script>

<template>
    <el-dialog :visible.sync="visible" width="30%"
    :close-on-click-modal="false" :before-close="handleClose">
        <div slot="title" class="dialog-title">
            <span class="title-text">编辑奖惩</span>
        </div>
        <Form 
            ref="form"
            :employeeOptions="employeeOptions"
            :fetchEmployeeOptionsFn="fetchEmployees"
            :loading="isActionDisabled"
            :disabled="isActionDisabled"
            v-model="form"
        />
        <div slot="footer" class="dialog-footer">
            <el-button
                @click="closeDialog" 
                :disabled="isSubmitting"
            >
                取 消
            </el-button>
            <el-button 
                type="primary" 
                :disabled="isActionDisabled" 
                :loading="isSubmitting" 
                @click="handleConfirm"
            >
                确 定
            </el-button>
        </div>
    </el-dialog>
</template>

<style lang="scss" scoped>
.dialog-title {
  position: relative;
  padding-bottom: 10px;
  .title-text{
    position: absolute;
    left: 20px;
    font-size: 20px;
  }
}
::v-deep .el-dialog__headerbtn {
    font-size: 24px;
}
::v-deep .el-dialog__header{
    padding: 20px 0;
    padding-bottom: 10px;
}
::v-deep .el-dialog__body{
    padding: 30px 0;
}
</style>